﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;

namespace ClassCommon
{
    /// <summary>
    /// 文件上传帮助类
    /// </summary>
    public static class HttpPostFileHelper
    {
        /// <summary>
        /// 用户文件上传
        /// </summary>
        /// <param name="name">input type="file" name</param>
        /// <returns>返回文件存储路径</returns>
        public static UploadFileInfo FileUploadAndSave()
        {
            HttpFileCollection files = HttpContext.Current.Request.Files;
            if (files == null) throw new Exception("上传的文件为空了，请检查fileName");
            // 
            string serverName = files.AllKeys.FirstOrDefault();

            HttpPostedFile file = HttpContext.Current.Request.Files[serverName];
            string originName = file.FileName;
            string extensionName = Path.GetExtension(file.FileName);
            string newName = DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(9999).ToString() + extensionName;
            string savePath = string.Format("/upload/{0}",  newName);
            string diskPath = HttpContext.Current.Server.MapPath(savePath);

            file.SaveAs(diskPath);


            UploadFileInfo fileInfo = new UploadFileInfo();
            fileInfo.orginName = originName;
            fileInfo.newName = newName;
            fileInfo.savePath = savePath;
            fileInfo.extensionName = extensionName;
            fileInfo.fileSize = file.ContentLength;
            fileInfo.contentType = file.ContentType;

            return fileInfo;
        }
    }

    public class UploadFileInfo
    {
        public string orginName { get; set; }
        public string newName { get; set; }
        public int fileSize { get; set; }
        public string extensionName { get; set; }
        public string savePath { get; set; }
        public string contentType { get; set; }
    }
}
